<template>
  <a-layout class="layout">
    <a-layout-sider
      v-model:collapsed="collapsed"
      :trigger="null"
      collapsible
      class="layout-sider"
    >
      <div class="logo">
        <img src="@/assets/logo.png" alt="Logo" />
        <h1 v-show="!collapsed">学伴助手后台</h1>
      </div>
      <a-menu
        v-model:selectedKeys="selectedKeys"
        theme="dark"
        mode="inline"
        :items="menuItems"
        @click="handleMenuClick"
      />
    </a-layout-sider>
    <a-layout>
      <a-layout-header class="layout-header">
        <div class="header-left">
          <menu-unfold-outlined
            v-if="collapsed"
            class="trigger"
            @click="() => (collapsed = !collapsed)"
          />
          <menu-fold-outlined
            v-else
            class="trigger"
            @click="() => (collapsed = !collapsed)"
          />
        </div>
        <div class="header-right">
          <a-dropdown>
            <div class="user-info">
              <a-avatar :src="userInfo?.avatar || ''" />
              <span class="username">{{ userInfo?.realName || '用户' }}</span>
            </div>
            <template #overlay>
              <a-menu>
                <a-menu-item @click="goToProfile">
                  <user-outlined />
                  个人中心
                </a-menu-item>
                <a-menu-item @click="handleLogout">
                  <logout-outlined />
                  退出登录
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </a-layout-header>
      <a-layout-content class="layout-content">
        <div class="content-wrapper">
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <keep-alive :include="cachedViews">
                <component :is="Component" />
              </keep-alive>
            </transition>
          </router-view>
        </div>
      </a-layout-content>
    </a-layout>
  </a-layout>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch, h } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { 
  MenuUnfoldOutlined, 
  MenuFoldOutlined, 
  UserOutlined, 
  LogoutOutlined,
  DashboardOutlined,
  BookOutlined,
  SolutionOutlined,
  UserSwitchOutlined,
  CheckCircleOutlined
} from '@ant-design/icons-vue'
import { useUserStore } from '@/store/user'
import { message } from 'ant-design-vue'

// 侧边栏折叠状态
const collapsed = ref(false)
// 选中的菜单项
const selectedKeys = ref<string[]>([])
// 路由缓存的组件
const cachedViews = ref<string[]>(['Dashboard'])

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 用户信息
const userInfo = computed(() => userStore.userInfo)
// 用户角色
const userRoles = computed(() => userStore.userRoles)

// 处理菜单权限
const hasPermission = (roles: string[] | undefined) => {
  if (!roles || roles.length === 0) return true
  return userRoles.value.some(role => roles.includes(role))
}

// 侧边栏菜单配置
const menuItems = computed(() => {
  const items = [
    {
      key: '/dashboard',
      icon: () => h(DashboardOutlined),
      label: '控制台',
      roles: undefined,
    },
    {
      key: '/user',
      icon: () => h(UserSwitchOutlined),
      label: '用户管理',
      roles: ['admin','teacher'],
    },
    {
      key: '/assignment',
      icon: () => h(BookOutlined),
      label: '作业管理',
      roles: ['admin', 'teacher'],
    },
    {
      key: '/student',
      icon: () => h(SolutionOutlined),
      label: '学生作业管理',
      roles: ['admin', 'teacher', 'student'],
    },
    {
      key: '/apikey',
      icon: () => h(CheckCircleOutlined),
      label: '大模型管理',
      roles: ['admin', 'teacher','student'],
    }
  ]
  
  // 根据用户角色过滤菜单项
  return items
    .filter(item => hasPermission(item.roles))
    .map(item => ({
      key: item.key,
      icon: item.icon,
      label: item.label,
    }))
})

// 监听路由变化
watch(
  () => route.path,
  (path) => {
    // 对于子路由，我们需要加上斜杠以匹配菜单key
    const menuKey = path === '/' ? '/dashboard' : `/${path.split('/').pop()}`
    selectedKeys.value = [menuKey]
    console.log('Current route path:', path, 'Selected key:', menuKey)
  },
  { immediate: true }
)

// 菜单点击事件
const handleMenuClick = ({ key }: { key: string }) => {
  console.log('Menu clicked:', key) // 添加日志以便调试
  // 使用完整路径进行导航，因为路由配置中使用了别名
  router.push(key)
}

// 跳转到个人中心
const goToProfile = () => {
  router.push('/profile')
}

// 退出登录
const handleLogout = async () => {
  try {
    await userStore.logout()
    message.success('退出登录成功')
    router.push('/login')
  } catch (error) {
    console.error('退出登录失败', error)
  }
}

// 组件挂载时
onMounted(() => {
  const path = route.path
  const menuKey = path === '/' ? '/dashboard' : `/${path.split('/').pop()}`
  selectedKeys.value = [menuKey]
  console.log('Mounted route path:', path, 'Selected key:', menuKey)
})
</script>

<style lang="less" scoped>
.layout {
  height: 100%;
  
  .layout-sider {
    box-shadow: 2px 0 8px 0 rgba(29, 35, 41, 0.05);
    
    .logo {
      height: 64px;
      padding: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #001529;
      
      img {
        height: 32px;
        width: 32px;
        margin-right: 12px;
      }
      
      h1 {
        color: white;
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        white-space: nowrap;
      }
    }
  }
  
  .layout-header {
    padding: 0 16px;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
    z-index: 10;
    
    .trigger {
      font-size: 18px;
      cursor: pointer;
      transition: color 0.3s;
      
      &:hover {
        color: var(--primary-color);
      }
    }
    
    .user-info {
      display: flex;
      align-items: center;
      cursor: pointer;
      
      .username {
        margin-left: 8px;
      }
    }
  }
  
  .layout-content {
    margin: 24px 16px;
    overflow: auto;
    
    .content-wrapper {
      padding: 24px;
      background: #fff;
      min-height: 100%;
    }
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style> 